/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.srwl.mytx.widget.chatRow;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.util.Log;

import com.srwl.mytx.domain.Message;
import com.srwl.mytx.Helper;
import com.srwl.mytx.utils.Utils;

import java.io.File;

/**
 * 语音row播放点击事件监听
 */
public class ChatRowAudioPlayer {
    private static final String TAG = "ChatRowAudioPlayer";
    private static String currentPlayingMsgId;
    private final AudioManager audioManager;
    private AudioPlayerInteractionListener mPlayerListener;
    private Message message;
    private MediaPlayer mediaPlayer = null;

    private static ChatRowAudioPlayer ourInstance = null;

    public static ChatRowAudioPlayer getInstance(Context context) {
        if (ourInstance == null) {
            synchronized (ChatRowAudioPlayer.class) {
                ourInstance = new ChatRowAudioPlayer(context);
            }
        }

        return ourInstance;
    }

    private ChatRowAudioPlayer(Context context) {
        Context baseContext = context.getApplicationContext();
        audioManager = (AudioManager) baseContext.getSystemService(Context.AUDIO_SERVICE);
        mediaPlayer = new MediaPlayer();
    }

    public void play(Message message, AudioPlayerInteractionListener mPlayerListener) {
        if (mediaPlayer.isPlaying()) {
            //如果在播放，就停止播放，并通过接口通知出去
            stopPlayVoice();
            if (this.mPlayerListener != null) {
                this.mPlayerListener.onBreakPlay();
            }
            //如果是正在播放的的item被点击了，那么return;
            if (currentPlayingMsgId != null && currentPlayingMsgId.equals(message.getId())) {
                currentPlayingMsgId = null;
                return;
            }
        }
        //设置新的药播放的消息对象和播放监听
        this.message = message;
        this.mPlayerListener = mPlayerListener;
        startPlayAudio();
    }

    public void setInteractionListener(AudioPlayerInteractionListener mPlayerListener) {
        this.mPlayerListener = mPlayerListener;
    }


    public boolean isPlaying() {
        return mediaPlayer.isPlaying();
    }

    public boolean isCurrentMsgPlaying(Message message) {
        return this.message.getId() == message.getId();
    }

    private void playVoice(String filePath) {

        currentPlayingMsgId = message.getId();
        //if (EaseUI.getInstance().getSettingsProvider().isSpeakerOpened()) {
        audioManager.setMode(AudioManager.MODE_NORMAL);
        audioManager.setSpeakerphoneOn(true);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

//        } else {
//            audioManager.setSpeakerphoneOn(false);// 关闭扬声器
//            // 把声音设定成Earpiece（听筒）出来，设定为正在通话中
//            audioManager.setMode(AudioManager.MODE_IN_CALL);
//            mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
//        }
        try {
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepare();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {

                    stopPlayVoice();
                    if (mPlayerListener != null) {
                        mPlayerListener.onCompletePlay();
                        // TODO: 2019/11/14 不能直接清除  mPlayerListener ，否则无法联系自动播放语音信息,
                        // mPlayerListener = null;
                    } else {
                        Log.e(TAG, "onCompletion: 播放完成，监听为空，没法通知");
                    }
                }
            });
            mediaPlayer.start();
            if (mPlayerListener != null) {
                mPlayerListener.onStartPlay();
            }

        } catch (Exception e) {
            Log.e(TAG, "播放语音出错：" + e.getMessage());
            if (mPlayerListener != null) {
                mPlayerListener.onError(1, e.getMessage());
            }
        }
    }

    /**
     * 开始播放
     */
    public void startPlayAudio() {

        String localFilePath = message.getLocalFilePath();
        if (!TextUtils.isEmpty(localFilePath)) {
            //发送的消息，content 里面是本地文件路径
            File file = new File(localFilePath);
            if (file.exists() && file.isFile()) {
                playVoice(localFilePath);
            } else {
                Log.e(TAG, "startPlayAudio: 语音文件不存在 messageId:" + message.getId());
                // TODO: 2019/6/15 如果是发送成功的文件，可以去下载远程文件
                if (mPlayerListener != null) {
                    mPlayerListener.onError(-1, "消息对应的本地语音文件不存在");
                }
            }

        } else {
            String content = message.getContent();

            String path = Helper.getInstance().getFilePath() + File.separator + content;
            File file = new File(path);
            if (file.exists() && file.isFile()) {
                playVoice(path);
            } else {
                Log.e(TAG, "startPlayAudio: 语音文件不存在 messageId:" + message.getId());
                if (mPlayerListener != null) {
                    mPlayerListener.onError(-1, "消息对应的本地语音文件不存在");
                }
            }
        }


    }

    /**
     * 停止播放
     */
    private void stopPlayVoice() {

        mediaPlayer.stop();
        mediaPlayer.reset();

    }


    /**
     * 中断播放，并清空 回调，避免别漏
     */
    public void breakPlay() {

        stopPlayVoice();
        if (this.mPlayerListener != null) {
            this.mPlayerListener.onBreakPlay();
            mPlayerListener = null;
        }

    }

    public interface AudioPlayerInteractionListener {
        //开始语音播放
        void onStartPlay();

        //中断播放
        void onBreakPlay();

        //语音播放完成
        void onCompletePlay();

        //播放
        void onError(int errorCode, String message);
    }

}
